import utils from '@/common/request.js'
import Vue from 'vue'
class webSocketClass {
	constructor(url, time, ucId) {
		this.ucId = ucId
		this.url = url
		this.data = null
		this.isCreate = false // WebSocket 是否创建成功
		this.isConnect = false // 是否已经连接
		this.isInitiative = false // 是否主动断开
		this.timeoutNumber = time // 心跳检测间隔
		this.heartbeatTimer = null // 心跳检测定时器
		this.reconnectTimer = null // 断线重连定时器
		this.socketExamples = null // websocket实例
		this.againTime = 3 // 重连等待时间(单位秒)
		this.innerAudioContext = null
	}

	// 初始化websocket连接
	initSocket() {
		const _this = this
		this.socketExamples = uni.connectSocket({
			url: _this.url,
			header: {
				'content-type': 'application/json'
			},
			success: (res) => {
				_this.isCreate = true
			},
			fail: (rej) => {
				_this.isCreate = false
			}
		})
		this.createSocket()
	}

	// 创建websocket连接
	createSocket() {
		if (this.isCreate) {
			// 监听 WebSocket 连接打开事件
			try {
				this.socketExamples.onOpen(() => {
					this.isConnect = true
					clearInterval(this.heartbeatTimer)
					clearTimeout(this.reconnectTimer)
					// 打开心跳检测
					this.heartbeatCheck()
				})
				// 监听 WebSocket 接受到服务器的消息事件
				this.socketExamples.onMessage((res) => {
					this.getMessage(res)
				})
				// 监听 WebSocket 连接关闭事件
				this.socketExamples.onClose(() => {
					this.isConnect = false
					this.reconnect()
				})
				// 监听 WebSocket 错误事件
				this.socketExamples.onError((res) => {
					this.isInitiative = false
				})
			} catch (error) {
				console.warn(error)
			}
		}
	}

	playAudio(path) {
		this.innerAudioContext = uni.createInnerAudioContext({
			useWebAudioImplement: false
		})
		this.innerAudioContext.src = path
		this.innerAudioContext.loop = true
		this.innerAudioContext.play()
		console.log(this)
	}
	stopAudio() {
		if (this.innerAudioContext) {
			this.innerAudioContext.stop()
			this.innerAudioContext.destroy()
		}
	}
	sub(parseData) {

		if (parseData.audio == 'true') {
			this.stopAudio()
		}
		if (parseData.audioOpen == 'true') {
			this.stopAudio()
			uni.navigateTo({
				url: '../../yzqy/bjcg/bjcg?noticeId=' + parseData.noticeInfoId + '&audioId=' +
					parseData.audioId + "&fireInfoId=" + parseData.taskId
			})
		} else {
			uni.navigateBack({
				delta: 2,
				success: () => {
					let page = getCurrentPages().pop()
					if (!page) {
						return;
					} else {
						let option = {
							type: 'refreshPage'
						}
						page.onShow(option)
					}
				}
			})
		}
		let that = this
		utils.request({
			url: 'wx/notice/updateReadStatus',
			data: {
				"ucId": parseData.noticeInfoId
			}
		}, {
			'authorization': uni.getStorageSync('authorization')
		}).then(function (res) {}).catch(function (e) {})

		if (parseData.equRounds == 'true') {
			uni.navigateTo({
				url: '../../yzqy/yjxq/yjxq?ucId=' + that.ucId + '&noticeInfoId=' + that.noticeInfoId
			})
		}
	}

	goToFire(parseData) {
		uni.navigateTo({
			url: '../../yzqy/hqxq/hqxq?ucId=' + parseData.ucId
		})
	}

	getMessage(msg) {
		let that = this
		let parseData = JSON.parse(msg.data)
		var pages = getCurrentPages();
		var page = pages[pages.length - 1];
		that.noticeInfo = parseData
		switch (parseData.type) {
			case 'notice':
				console.log(parseData)
				if (parseData.audio == 'true') {
					that.playAudio("https://www.cetczhxf.com/mp3/alarm.mp3")
				} else {
					that.stopAudio()
				}

				if (parseData.hasOwnProperty('equRounds') && parseData.equRounds == 'true') {
					that.ucId = parseData.alarmInfoId
				}
				if (parseData.infoType == "2") {
					that.noticeInfoId = parseData.noticeInfoId
					that.audioId = parseData.audioId
					// uni.showModal({
					// 	title: '发现火情',
					// 	content: parseData.message,
					// 	confirmText: "确认", // 确认按钮文字
					// 	showCancel: false, // 是否显示取消按钮，默认为 true
					// 	confirmColor: '#f55850',
					// 	success: (res) => {
					// 		if (res.confirm) {
					// 			that.sub(parseData)
					// 		}
					// 	}
					// })

					Vue.prototype.$showPrompt({
						title: '发现火情',
						message: parseData.message,
						buttonName: '立即处理',
						confirm: data => {
							that.sub(parseData)
						}
					});
				}
				if (parseData.infoType == "1") {
					that.noticeInfoId = parseData.noticeInfoId
					that.audioId = parseData.audioId

					Vue.prototype.$showPrompt({
						title: '火情预警',
						message: parseData.message,
						buttonName: '立即处理',
						confirm: data => {
							that.sub(parseData)
						}
					});
				}
				if (parseData.infoType == "0") {
					if (parseData.audioOpen == 'false') {
						that.stopAudio()
					}
					that.noticeInfoId = parseData.noticeInfoId
					that.audioId = parseData.audioId
					Vue.prototype.$showPrompt({
						title: '火情结束',
						message: parseData.message,
						buttonName: '确认',
						bgImage: 1,
						confirm: data => {
							that.stopAudio()
							if (page.route == 'yzqy/bjcg/bjcg' || page.route == 'yzqy/hqxq/hqxq') {
								uni.navigateTo({
									url: '../../pages/index/index'
								})
							}
						}
					});
				}
				break;
			case "fireStop":
				Vue.prototype.$showPrompt({
					title: parseData.title,
					message: parseData.message,
					buttonName: '确认',
					bgImage: 1,
					confirm: data => {
						that.stopAudio()
						if ((page.route == 'yzqy/bjcg/bjcg' || page.route == 'yzqy/hqxq/hqxq') && parseData.title == '火情结束') {
							uni.navigateTo({
								url: '../../pages/index/index'
							})
						}
					}
				});
				break;
			case 'fireAlarm':
				that.playAudio("https://www.cetczhxf.com/mp3/alarm.mp3")
				// uni.showModal({
				// 	title: '火情预警',
				// 	content: '【' + parseData.enterpriseName + '】' + parseData.buildName + ',' + parseData.name,
				// 	confirmText: "确认", // 确认按钮文字
				// 	showCancel: false, // 是否显示取消按钮，默认为 true
				// 	confirmColor: '#f55850',
				// 	success: (res) => {
				// 		if (res.confirm) {
				// 			that.goToFire(parseData)
				// 		}
				// 	}
				// })
				Vue.prototype.$showPrompt({
					title: '火情预警',
					message: '【' + parseData.enterpriseName + '】' + parseData.buildName + ',' + parseData.name,
					buttonName: '立即处理',
					confirm: data => {
						that.goToFire(parseData)
					}
				});
				break;
			case "refresh":
				if (page.route == 'wb/wbxq/wbxq' || page.route == 'yzqy/hqxq/hqxq') {
					uni.redirectTo({
						url: page.$page.fullPath
					});
				}
				break;
			case "wbmessage":
				uni.showModal({
					title: '提示',
					content: parseData.message,
					cancelText: "未检测", // 取消按钮的文字
					confirmText: "检测", // 确认按钮文字
					showCancel: true, // 是否显示取消按钮，默认为 true
					confirmColor: '#f55850',
					cancelColor: '#39B54A',
					success: (res) => {
						if (res.confirm) {
							let params = {
								"ucId": parseData.equcid,
								"modelId": parseData.modelId
							}
							app.globalData.request({
								url: '/wx/maintenance/wbCheck',
								data: params
							}).then(res => {})
						} else if (res.cancel) {
							let params = {
								"ucId": parseData.equcid
							}
							app.globalData.request({
								url: '/wx/maintenance/wbFire',
								data: params
							}).then(res => {})

						}
					}
				})
				// Vue.prototype.$showPrompt({
				// 	title: '提示',
				// 	message: parseData.message,
				// 	confirm: data => {
				// 		that.goToFire(parseData)
				// 	}
				// });
				break;
			default:
				break;
		}
	}
	// 发送消息
	sendMsg(value) {
		const param = JSON.stringify(value)
		return new Promise((resolve, reject) => {
			this.socketExamples.send({
				data: param,
				success() {
					resolve(true)
				},
				fail(error) {
					reject(error)
				}
			})
		})
	}

	// 开启心跳检测
	heartbeatCheck() {
		this.data = {
			"type": "heartbeat",
			"ucId": this.ucId
		}
		this.heartbeatTimer = setInterval(() => {
			this.sendMsg(this.data)
		}, this.timeoutNumber * 1000)
	}

	// 重新连接
	reconnect() {
		// 停止发送心跳
		clearTimeout(this.reconnectTimer)
		clearInterval(this.heartbeatTimer)
		// 如果不是人为关闭的话，进行重连
		if (!this.isInitiative) {
			this.reconnectTimer = setTimeout(() => {
				this.initSocket()
			}, this.againTime * 1000)
		}
	}

	// 关闭 WebSocket 连接
	closeSocket(reason = '关闭') {
		const _this = this
		this.socketExamples.close({
			reason,
			success() {
				_this.data = null
				_this.isCreate = false
				_this.isConnect = false
				_this.isInitiative = true
				_this.socketExamples = null
				clearInterval(_this.heartbeatTimer)
				clearTimeout(_this.reconnectTimer)
			},
			fail() {}
		})
	}
}

export default webSocketClass